package com.explorati.LeetCode202.happynumber;

import java.util.ArrayList;

/**
 * 202. Happy Number 每个位的加和若不等于1 则会是重复的
 * 
 * 详细见原题 Starting with any positive integer, replace the number by the sum of
 * the squares of its digits, and repeat the process until the number equals 1
 * (where it will stay), or it loops endlessly in a cycle which does not include
 * 1. Those numbers for which this process ends in 1 are happy numbers.
 * 
 * @author explorati
 *
 */
public class Solution {
	public boolean isHappy(int n) {
		// 使用list记录是否有重复元素出现，若有，直接返回false
		ArrayList<Integer> list = new ArrayList<Integer>();
		while (true) {
			int sum = 0;
			while (n / 10 > 0 || n % 10 > 0) {
				sum += (n % 10) * (n % 10);
				n = n / 10;
			}
			if (sum == 1) {
				return true;
			}
			if (list.contains(sum)) {
				return false;
			} else {
				list.add(sum);
			}
			n = sum;
		}
	}
}
